$import("biz.base.StoreHelper,biz.base.FormEditorUtil,biz.base.RenderUtil,biz.base.GridEditorUtil,biz.base.CompositePanel"); 
$import('biz.ext3.examples.ux.TabCloseMenu');
$import('biz.ext3.examples.ux.TabScrollerMenu');



var clrMap = {
	"0" : "#000",
	"1" : "#000",
	"2" : "#00f",
	"-1" : "#f00"
};

function getUserMenuMacePanel(userMenuMaceMetaId){
	var attrMap=metaData["attrs"],metas=attrMap["meta"],refMetaMap=metaData["refMetaMap"],
	userMaceMeta=metas["mace"],menuMetaId=userMaceMeta["menu"],
	menuMaceModel=refMetaMap[menuMetaId],
	menuMaceMeta=menuMaceModel["attrs"]["meta"],
	menuMetaId=menuMaceMeta["fid"],
	menuMeta=refMetaMap[menuMetaId],
	menuMetaAttrs=menuMeta["attrs"];
	var menuRootId=menuMetaAttrs["rootId"],
	menuMaceRankId=menuMetaAttrs["rank"]["mace"],
	
	menuMetaModels=menuMetaAttrs["meta"],
	menuActionMetaId=menuMetaModels["action"],
	menuPageMetaId=menuMetaModels["page"],
	menuGroupMetaId=menuMetaModels["group"];
	 function collectMod(node, o) {// 收集用户所做的修改
			var attrs = node.attributes,id=attrs["id"],fid=attrs["fid"],type=attrs["meta"],act=attrs["act"];
			switch (attrs["state"]) {
			case -1:
				if(type==menuActionMetaId){
					var oldAct=o[fid];
					if(oldAct&&act){
						if(oldAct&act==act){
							var nAct=oldAct&~act;
							o[fid]=nAct;
						}
					}else{
						
					}
				}else{
					o[id]=0;
				}
				break;
			case 2:
				if(type==menuActionMetaId){
					var oldAct=o[fid];
					if(oldAct&&act){
						if(oldAct&act!=act){
							var nAct=oldAct|act;
							o[fid]=nAct;
						}
					}else{
						o[fid]=act;
					}
				}else{
					if(o[id]){
						o[id]=act|o[id];
					}else{
						o[id]=act;
					}
					
				}
				break;
			default:
				break;
			}
			node.expand();
			node.eachChild(function(child) {
				collectMod(child, o);
			});
		}
	var treeLoader = new Ext.tree.TreeLoader({dataUrl:'../mace/getMenuTree',
		baseAttrs:{checked:false,expanded:true}});
	var checkTree= new Ext.tree.TreePanel({
        region:'west',
        id:'menuMace',
        title:'菜单权限',
        split:true,
        autoScroll: true,
        width: 200,
        root:new Ext.tree.AsyncTreeNode({id:menuRootId,text:'根节点'}),
        animate: true,
        minSize: 175,
        maxSize: 400,
        expanded : true,
        collapsible: false,
        floatable: false,
        tbar:[{
			xtype : 'button',
			text : '保存',
			iconCls : 'icon-submit',
			tooltip : {
				text : '保存新增或删除的权限'
			},
			handler : function() {
				var row=Ext.getCmp('user_grid')["cur_row"];
				if (!row)
					return Ext.Msg.alert('提示','请先选择要操作的用户!');
				var o = {uid: row.get("SID"),maceMap:{}},maceMap=o["maceMap"];
				collectMod(checkTree.getRootNode(),maceMap);
				if (maceMap.length == 0)
					return Ext.Msg.alert('提示','没有改动，无需提交!');
				var url = "../mace/batchSave";
				checkMace(checkTree, rs["data"]);
			}
		} ,{
			xtype : 'button',
			text : '刷新',
			iconCls : 'icon-reload',
			tooltip : {
				text : '刷新权限'
			},
			handler:function(){
				var checkTree=Ext.getCmp('menuMace');
				checkTree.getRootNode().reload();
			}}],
			listeners : {
				'checkchange' : function(node, checked) {
					
					var sels=Ext.getCmp('user_grid').selModel.getSelections();
					if (sels.length==0){
						node.ui.checkbox.checked = false;
						node.attributes.checked = false;
						return Ext.Msg.alert('提示','请先选择用户!');
					}
					checkChildren(node, checked);
					checkParent(node);
				}
			},
        titleCollapse:true,
        margins:'0 0 0 1',	
        rootVisible: false,
	       lines: false,
	       border:false,
	       useArrows: true,		       
	       loader: treeLoader,
	       root: new Ext.tree.AsyncTreeNode({id:'ccc',text:'根节点'}),
	       listeners:{
	    	   'load':function(){
	      			var sels=Ext.getCmp('user_grid').getSelectionModel().getSelections();
	      			if(sels.length==0)return ;
	      			var row=sels[0];
	      			var url="../mace/getMaceMap?uid="+row.get("SID")+"&rank="+menuMaceRankId;
	      			$.get(url,function(rs){
	      				var roleIds	= rs["data"];
	    	       	 	roleIds.push(row.get("META"));
	      			});
	      		}	
	       }
           
});
	return checkTree;
}
function  getUserRoleMacePanel(){
	var companel = new CompositePanel('BT_ROLE');
		companel.initBefore=function(){
	      	this.dataConfig.idProperty="SID";
	      	this.dataConfig.sortInfo={field:"SID",direction:"DESC"};
	      	var bs=this.dataConfig.baseParams;
	      	this.showColumns=["NAME","TEXT"];
	      	bs["filter.UNID"]=unid;
	       	this.gridConfig.xtype='grid';
	       	this.gridConfig.id='role_grid';
	       	this.gridConfig.clicksToEdit='auto';
	       	this.gridConfig.renderTo=null;
	       	this.gridConfig.region='west';
	      	this.gridConfig.filter=true;
	    	this.gridConfig.split=true;
	      	this.gridConfig.width = 300;
	      	this.dataConfig.listeners={
	      		'load':function(){
	      			
	       	 		
	      		}	
	      	};
	      	this.doCommit=function(){
	        	var sels=Ext.getCmp('user_grid').selModel.getSelections();
	     	   if(sels.length==0)return Ext.Msg.alert('提示','请先选择要操作的用户！');
	     	   var row=sels[0],uri="module/Mace-batchRoles.action?jsonStr=";
	     	   var postData={uid:row.get("SID"),adds:[],dels:[]};
	     	   collectData(Ext.getCmp('role_grid'),postData);
	     	   if(postData["adds"].length==0&&postData["dels"].length==0)
	     		   return Ext.Msg.alert('提示','没有修改，无需提交!');
	     	   var rs=Ext.decode(doHttpPost(uri+Ext.encode(postData)).text),ids=rs["data"];
	     	   ids.push(row.get("META")); 
	     	  checkGridRow(this.gridPanel,ids);
	        };
	      	this.gridConfig.selModel=new Ext.grid.CheckboxSelectionModel({singleSelect : false
	      		,handleMouseDown: Ext.emptyFn,
	      		listeners:{
	         		'rowselect':function(sm,rowIndex,record){
	         			var sm=Ext.getCmp('user_grid').selModel,sels=sm.getSelections(),
	         			roleGrid=Ext.getCmp('role_grid');
	         			if(sels.length==0){
	         				sm.deselectRow(rowIndex);
	         				return Ext.Msg.alert('提示','请先选择要操作的用户！');}
	                     var view = roleGrid.getView();
	                     var row=roleGrid.store.getAt(rowIndex);
	                     row["state"]+=2;
	                 	view.getRow(rowIndex).style.color=clrMap[row["state"]+""];
	                   },
	                   'rowdeselect':function(sm,rowIndex,record){
	                	   var sm=Ext.getCmp('user_grid').selModel,sels=sm.getSelections(),
		         			roleGrid=Ext.getCmp('role_grid');
		         			if(sels.length==0)return;
	                 	  var view = roleGrid.getView();
	                 	  var row=roleGrid.store.getAt(rowIndex);
	                 	  row["state"]-=2;
	                 	  view.getRow(rowIndex).style.color=clrMap[row["state"]+""];
	                   }
	         	}});
		};
	       companel.formConfig=false;
	       companel.gridConfig.title='角色列表';
	       companel.gridConfig.tbar=companel.getButtons(['doReload','doCommit']);

	   	companel.display();
	     return companel.gridPanel;
}

function getMaceWin(){
	var maceWin=Ext.getCmp('maceWin');
	if(!maceWin){
		var userMenuMace=getUserMenuMacePanel();
		var userRoleMace=getUserRoleMacePanel();
		var tabPanel=new Ext.TabPanel({
	        id:'maceTab',
	        region:'center',
	        deferredRender:false,
	        enableTabScroll:true,
	        autoScroll: true,
	        autoWidth:false,
	        activeTab:0,
	        bodyCssClass :'bgFilter',
	        plugins: [new Ext.ux.TabCloseMenu()],
	        items:[userMenuMace,userRoleMace]});
		maceWin= new Ext.Window({
		      layout:'border',
		      id:'maceWin',
		      scrollable:true,
		      modal:true,
		      title:'权限分配',
		      width:800,
		      height:480,
		      plain: true,
		      items: tabPanel
			 });
		}
	var menuMace=Ext.getCmp('menuMace'),userGrid=Ext.getCmp('user_grid'),
	selModel=userGrid.getSelectionModel(),sels=selModel.getSelections(),sel=sels[0],
	unitId=sel.get("UNID");
	roleGrid=Ext.getCmp('role_grid');
	roleGrid.store.baseParams["filter.UNID"]=unid;
	roleGrid.store.reload();
	return  maceWin.show();
}


function initUserGrid(){
	var userMetaData={};
	Ext.apply(userMetaData,metaData);
	Ext.apply(userMetaData,metaData["attrs"]);
	var companel = new CompositePanel({metaData:userMetaData});
	companel.initBefore=function(){
	    this.gridConfig.title='用户列表';
      	var bs=this.dataConfig["baseParams"]=this.dataConfig["baseParams"]||{};
		bs["filter.UNID"]=unid;
		bs["filter.FID"]=unid;
		bs["filter.RANK"]=this.metaData["id"];
		bs["filter.FLAG"]=1;
       	this.gridConfig.xtype='editorgrid';
      	this.gridConfig.id="user_grid";
       };
       companel.handlers.put('doMace',{text:'权限',iconCls:'icon-finish', tooltip:{text:'权限控制',title:'权限控制'}});
   	
       companel.gridConfig.tbar = companel.getButtons([ 'doAddNew','doModify','doDelete', 'splitter', 'doReload', 'doCommit','doMace']);
      
       companel.singleClick=function(grid, rowindex, e){
       };
       
       companel.doMace=function(){
   		getMaceWin();
   	};
		companel.doubleClick=function(){};
       companel.display();
       return companel.gridPanel;
}
function cacheFormData(){
	var form=Ext.getCmp('detail_form');
	var grid=Ext.getCmp('user_grid');
	var cur_row=grid["cur_row"];
	if(!cur_row)return;
	if(form.getForm().isDirty()){
		 form.items.each(function(item,index,length){
			 if(item.originalValue!=item.getValue()){
				 cur_row.set(item["rawName"],item.getValue());
			 }
		});
	}
}


Ext.onReady(function(){
      Ext.QuickTips.init();
      initUserGrid();
 });

function existInArray(id,ids){
	for(var i in ids){
		if(id==ids[i])
			return true;
	}
	return false;
}

function checkMace(treePanel, data) {
	var rootNode = treePanel.getRootNode();
	loadCheck(rootNode, data);
}

function loadCheck(node, maceIds) {//
	var attrs = node.attributes;
	if (!node.attributes.raw)
		node.attributes.raw = attrs["text"];
	var checked = existInArray(attrs["id"], maceIds);
	var a = node.ui.checkbox;
	if (a) {
		a.checked = checked;
		attrs.checked = checked;
		var old = node.attributes["state"];
		node.attributes["state"] = checked ? 1 : 0;// 默认选中
		if (old) {
			node.setText("<font color='" + clrMap[attrs["state"] + ""] + "'>"
					+ node.attributes.raw + "</font>");
		} else {
			node.setText("<font color='" + clrMap[attrs["state"] + ""] + "'>"
					+ node.attributes.raw + "</font>");
		}
	}
	node.expand();
	node.eachChild(function(child) {
		loadCheck(child, maceIds);
	});
}

function expandTree(tree){
	var rootNode=tree.getRootNode();
	expandNode(rootNode);
}
function expandNode(node){
	node.expand();
	node.eachChild(function(child) {
		expandNode(child);
	});
}
function loadOrgBelonged(row){
 var mid=row.get("MID");
 checkOrg(mid);
}

function getChoice(node,data){
	node.expand();
	node.eachChild(function(child) {
		 var a=child.ui.checkbox;
		 if(a&&a.checked){c= child.attributes.id;data.push(c);}
		 getChoice(child,data);
	});
}


	// state 0：默认未选，1：默认选中，2：新增，-1：删除
	function changeState(node, checked) {// 改变当前节点状态
		var attrs = node.attributes;
		var old = attrs["state"];
		if (attrs["state"] == null)
			return;
		if (checked) {
			if (attrs["state"] <= 0)
				attrs["state"] += 2;
		} else {
			if (attrs["state"] > 0)
				attrs["state"] -= 2;
		}
		if (old != attrs["state"])// change text color
			node.setText("<font color='" + clrMap[attrs["state"] + ""] + "'>"
					+ node.attributes.raw + "</font>");
	}

	function checkParent(node) {// 同步所有父节点
		var p = node.parentNode;
		if (!p)
			return;
		var a = p.ui.checkbox;
		if (node.attributes.checked) {
			if (a) {
				p.attributes.checked = true;
				a.checked = true;
				changeState(p, true);
				checkParent(p);
			}
		} else {
			var flag = true;
			p.eachChild(function(child) {
				if (child.attributes.checked) {
					flag = false;
					return;
				}
			});
			if (flag && a) {
				p.attributes.checked = false;
				a.checked = false;
				changeState(p, false);
				checkParent(p);
			}
		}
	}

	function checkChildren(node, checked) {// 同步所有子节点
		if (!node)
			return;
		node.expand();
		changeState(node, checked);
		node.eachChild(function(child) {
			var a = child.ui.checkbox;
			if (a) {
				a.checked = checked;
				child.attributes.checked = checked;
				checkChildren(child, checked);
			}
		});
	}